<?php
/**
 *
 * @author ling
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');

class Junsion_challengModuleProcessor extends WeModuleProcessor
{
    public function respond(){
        global $_W;
        
        if ($this->message['msgtype'] == 'event') {
			if ($this->message['event'] == 'subscribe') {
				$content = $this->message['content'];
				$wid = str_replace('junsion_challeng', '', $content);
        		$openid = $this->message['from'];
        		load()->model('mc');
        		$ACCESS_TOKEN = $this->getAccessToken();
        		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openid}&lang=zh_CN";
        		load()->func('communication');
        		$json = ihttp_get($url);
        		$userInfo = @json_decode($json['content'], true);
        		$unionid = $userInfo['unionid'];
        		if (empty($unionid)) return '';
        		$mem = pdo_fetch('select id from ' . tablename($this->modulename.'_mem') . " where unionid = '{$unionid}' and weid='{$wid}'");
        		if(!empty($mem)){
        			$first_num = pdo_fetch('select id from ' . tablename($this->modulename.'_nums') . " where mid = '{$mem['id']}' and type=2 and identity=".$_W['uniacid']);
        			if (!empty($first_num)) return '';
        			$cfg = pdo_fetch('select settings from '.tablename('uni_account_modules')." where uniacid='{$wid}' and module='junsion_challeng'");
        			if (empty($cfg)) return '';
        			$cfg = unserialize($cfg['settings']);
        			$w = $cfg['wechat'];
        			foreach ($w as $v) {
        				$ws[] = $v['wechat'];
        			}
        			if (!in_array($_W['uniacid'], $ws)) return '';
        			pdo_insert($this->modulename.'_nums',array('mid'=>$mem['id'],'type'=>2,'createtime'=>time(),'identity'=>$_W['uniacid']));
        			if ($cfg['guide_num'] > 0){
        				pdo_query("update ".tablename($this->modulename.'_mem')." set challeng_num=challeng_num+{$cfg['guide_num']} where id='{$mem['id']}' ");
        			}
        			if($cfg['type']==1){
        				if ($cfg['news']){
        					$news = json_decode($cfg['news'],true);
        					foreach ($news as $k=> $value) {
        						if (empty($value['txt'])) continue;
        						$response[$k] = array(
        								'title' =>  $value['txt'],
        								'picurl' => tomedia( $value['img']),
        								'url' =>$this->buildSiteUrl($value['url'])
        						);
        					}
        					ksort($response);
        					return $this->respNews($response);
        				}
        			}
        			else{
        				$img = IA_ROOT.'/attachment/'.$cfg['imgs'];
        				$media_id = $this->uploadImage($img);
        				return $this->respImage($media_id);
        			}
        		}else{
        			$w = $cfg['wechat'];
        			foreach ($w as $v) {
        				if ($wid == $v['wechat']) return $this->respText($cfg['reply']);
        			}
        			return '';
        		}
        	}
        }
    }
    
    private function getAccessToken() {
    	global $_W;
    	load()->model('account');
    	$acid = $_W['acid'];
    	if (empty($acid)) {
    		$acid = $_W['uniacid'];
    	}
    	$account = WeAccount::create($acid);
    	$token = $account->fetch_available_token();
    	return $token;
    }
    
    private function uploadImage($img)
    {
    	load()->func('communication');
    	$access_token = $this->getAccessToken();
    	$url = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image';
    	$ch1 = curl_init();
    	$data = array('media' => '@' . $img);
    	if (version_compare(PHP_VERSION, '5.5.0', '>')) {
    		$data = array('media' => curl_file_create($img));
    	}
    	curl_setopt($ch1, CURLOPT_URL, $url);
    	curl_setopt($ch1, CURLOPT_POST, 1);
    	curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
    	curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
    	curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
    	$content = @json_decode(curl_exec($ch1), true);
    	if (!(is_array($content))) {
    		$content = array('media_id' => '');
    	}
    	curl_close($ch1);
    	return $content['media_id'];
    }
    
}
